<template>
  <div class="w-card content-box">
    <div class="title-box">
      <span class="title">{{ titleText }}</span>
      <!-- <el-button style="margin-left:auto;" type="primary" plain @click="lookGoods">预览</el-button> -->
      <div style="margin-left: auto;"></div>
      <el-button v-show="isAdd" type="warning" plain @click="resetGoodsForm">重置</el-button>
      <el-button type="primary" @click="publishGoods">确定{{isAdd ? '发布' : '修改'}}商品</el-button>
    </div>
    <el-form class="form-box" style="margin-top: 20px;" ref="goodsFormRef" :model="goodsForm" :rules="goodsFormRules">
      <div class="f-title">上游平台信息</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="6">
          <el-form-item prop="channelCode" label="上游平台">
            <el-select :disabled="!isAdd" v-model="goodsForm.channelCode" placeholder="请选择上游平台" clearable>
              <el-option v-for="item in shangyouOptions" :key="item.channelCode" :label="item.channelName"
                :value="item.channelCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="channelGoodsCode" label="平台商品编码">
            <el-input :disabled="!isAdd" v-model="goodsForm.channelGoodsCode" placeholder="请输入平台商品编码" />
            <el-button type="primary" :loading="getChannelGoodsLoading" v-show="isAdd"
              @click="getChannelGoodsInfo(goodsForm.channelCode,goodsForm.channelGoodsCode)">获取商品信息</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="channelShopName" label="平台商户名称">
            <el-input disabled v-model="goodsForm.channelShopName" placeholder="请输入平台商户名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="f-title">商品基础信息</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="6">
          <el-form-item prop="goodsName" label="商品名称">
            <el-input v-model="goodsForm.goodsName" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="operator" label="运营商">
            <el-input disabled v-model="goodsForm.operator" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="belongingPlace" label="归属地">
            <el-input disabled v-model="goodsForm.belongingPlace" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="f-title" v-show="goodsForm.premoneyList && goodsForm.premoneyList.length > 0">可选预存</div>
      <div>
        <el-row :gutter="20" style="margin-top: 10px;" v-show="goodsForm.premoneyList && goodsForm.premoneyList.length > 0"
          v-for="(item,index) in goodsForm.premoneyList" :key="item">
          <el-col :span="4">
            <el-form-item prop="showMoney" label="预存面额">
              <el-input disabled v-model="item.showMoney" placeholder="请输入预存面额" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="payMoney" label="实付金额">
              <el-input disabled v-model="item.payMoney" placeholder="请输入实付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="activityTitle" label="活动标题">
              <el-input disabled v-model="item.activityTitle" placeholder="请输入活动标题" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="activityMsg" label="备注">
              <el-input disabled v-model="item.activityMsg" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- <div class="f-title">佣金配置</div>
      <div class="yongjin-box" style="margin-top: 10px;">
        <div v-for="(item,index) in goodsForm.incomeConfList" :key="item">
          <span style="flex-shrink: 0">佣金配置{{ index + 1 }}：</span>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :prop="'incomeConfList.'+index+'.runState'" :rules="goodsFormRules.chufa" label="触发条件">
                <el-select v-model="item.runState" placeholder="请选择触发条件" clearable>
                  <el-option v-for="items in chufaOptions" :key="items.value" :label="items.label" :value="items.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="佣金名称" :prop="'incomeConfList.'+index+'.incomeName'" :rules="goodsFormRules.yongjinName">
                <el-input v-model="item.incomeName" placeholder="请输入佣金名称" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="佣金(元)" :prop="'incomeConfList.'+index+'.income'" :rules="goodsFormRules.yongjin">
                <el-input v-model="item.income" type="number" placeholder="请输入佣金(元)" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :prop="'incomeConfList.'+index+'.gaveType'" :rules="goodsFormRules.fanyong" label="返佣模式">
                <el-select v-model="item.gaveType" placeholder="请选择返佣模式" clearable>
                  <el-option v-for="items in fanyongOptions" :key="items.value" :label="items.label" :value="items.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="`冻结期限(${item.gaveType == 1 ? '天' : item.gaveType == 2 ? '月' : '天'})`"
                :prop="'incomeConfList.'+index+'.freezenDay'" :rules="goodsFormRules.dongjieDay">
                <el-input v-model="item.freezenDay" type="number"
                  :placeholder="`请输入冻结期限(${item.gaveType == 1 ? '天' : item.gaveType == 2 ? '月' : '天'})`" />
              </el-form-item>
            </el-col>
            <el-icon class="remove-icon" @click="removeYongjinCinfig(item,index)">
              <Remove />
            </el-icon>
          </el-row>
        </div>
        <el-button type="primary" @click="addYongjinConfig">新增佣金配置</el-button>
      </div>
      <div class="f-title">分佣比例</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="6">
          <el-form-item prop="incomeDiscount" label="总部留存(‰)">
            <el-input v-model="goodsForm.incomeDiscount" type="number" placeholder="请输入总部留存(‰)" />
          </el-form-item>
        </el-col>
      </el-row> -->
      <div class="f-title">限制条件</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="24">
          <el-form-item prop="addressRestrictType" style="width:80%" label="发货地址限制">
            <el-radio-group v-model="goodsForm.addressRestrictType" @change="addressRestrictTypeChange">
              <el-radio :label="-1">不限制</el-radio>
              <el-radio :label="1">不发货地址
                <el-button v-if="goodsForm.addressRestrictType == 1" type="primary" style="margin-left:10px"
                  @click="noToHandle">已设置{{ (goodsForm.baseAreaInfoList && goodsForm.baseAreaInfoList.length) || 0 }}个</el-button>
              </el-radio>
              <el-radio :label="2">只发货地址
                <el-cascader v-if="goodsForm.addressRestrictType == 2" style="width:100%" v-model="goodsForm.baseAreaInfoList"
                  :options="provinces" :props="provincesProps" collapse-tags collapse-tags-tooltip placeholder="请选择只发货地址" />
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="24">
          <el-form-item prop="age" style="width:50%" label="年龄限制(周岁)">
            <el-input v-model="goodsForm.minAge" type="number" clearable placeholder="请输入最小年龄" />
            <span style="margin:0 10px">至</span>
            <el-input v-model="goodsForm.maxAge" type="number" clearable placeholder="请输入最大年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="f-title">一证N号限制</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="4">
          <el-form-item prop="idcardCheckDay" label="最近天数">
            <el-input v-model="goodsForm.idcardCheckDay" type="number" clearable placeholder="0为不限制" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="idcardCheckNum" label="开户数量">
            <el-input v-model="goodsForm.idcardCheckNum" type="number" clearable placeholder="0为不限制" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="f-title">商品详细信息</div>
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="6">
          <el-form-item prop="monthRent" label="月租(元)">
            <el-input v-model="goodsForm.monthRent" placeholder="请输入月租(元)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="monthFlow" label="流量(G)">
            <el-input v-model="goodsForm.monthFlow" placeholder="请输入流量(G)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="callPrice" label="语音价格(元/分钟)">
            <el-input v-model="goodsForm.callPrice" placeholder="请输入语音价格(元/分钟)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item prop="preferential" label="优惠">
            <el-input v-model="goodsForm.preferential" type="textarea" placeholder="请输入优惠" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item prop="headImg" style="width:80%" label="商品主图">
            <div v-show="!goodsForm.headImg" class="upload-box-img" @click="uploadImg">
              <el-icon>
                <Plus />
              </el-icon>
            </div>
            <div class="upload-box" v-show="goodsForm.headImg">
              <img :src="goodsForm.headImg" alt="">
              <el-icon color="#ffffff" class="upload-close" @click="removeImg">
                <Close />
              </el-icon>
            </div>
            <input ref="uploadInputRef" style="display:none" type="file" accept="image/*" @change="uploadChange">
            <span style="color:#808080;font-size:12px;margin-left: 10px;">提示：商品主图建议长宽比为1：1</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item prop="goodsDetail" label="商品详情">
            <Editor width="100%" v-model="goodsForm.goodsDetail" :api-key="apiKey" :init="init" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item prop="remark" label="备注">
            <el-input v-model="goodsForm.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <look-goods-vue ref="lookGoodsVueRef" />
  <no-to-add-dialog ref="noToAddDialogRef" @noToDialogClose="noToDialogClose" />
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import lookGoodsVue from '@/components/lookGoods.vue'
import noToAddDialog from '../components/noToAddDialog.vue'
import api from '../api'
import { errorDeal, warningDeal, getStore, successDeal } from '@/utils/utils'
import Editor from "@tinymce/tinymce-vue";
import axios from "axios"
export default {
  components: {
    lookGoodsVue,
    noToAddDialog,
    Editor,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const lookGoodsVueRef = ref(null)
    const noToAddDialogRef = ref(null)
    const goodsFormRef = ref(null)
    const uploadInputRef = ref(null)

    const imgUrlPass = (rule, value, callback) => {
      if (!state.goodsForm.headImg) {
        callback(new Error('请上传商品主图'))
      } else {
        callback()
      }
    }
    const agerules = (rule, value, callback) => {
      if (!state.goodsForm.minAge || !state.goodsForm.maxAge) {
        callback(new Error('请输入最大最小年龄'))
      }
      if (((state.goodsForm.minAge < 0) || (state.goodsForm.minAge > state.goodsForm.maxAge)) || ((state.goodsForm.maxAge < 0) || (state.goodsForm.maxAge > 100))) {
        callback(new Error('请输入正确年龄'))
      } else {
        callback()
      }
    }
    const incomeDiscountRules = (rule, value, callback) => {
      if (state.goodsForm.incomeDiscount != 0 && !state.goodsForm.incomeDiscount) {
        callback(new Error('请输入总部留存'))
        return
      }
      if ((state.goodsForm.incomeDiscount > 1000) || (state.goodsForm.incomeDiscount < 0)) {
        callback(new Error('请输入0-1000的数字'))
        return
      }
      callback()
    }

    const state = reactive({
      getChannelGoodsLoading: false,
      isAdd: true,
      titleText: null,
      editGoodsId: null,
      goodsForm: {
        incomeConfList: [{}],
      },
      goodsFormRules: {
        channelShopName: [
          { required: true, message: '请获取商品信息', trigger: 'blur' },
        ],
        belongingPlace: [
          { required: true, message: '请获取商品信息', trigger: 'blur' },
        ],
        operator: [
          { required: true, message: '请获取商品信息', trigger: 'blur' },
        ],
        channelGoodsCode: [
          { required: true, message: '请输入平台商品编码', trigger: 'blur' },
        ],
        channelCode: [
          { required: true, message: '请选择上游平台', trigger: 'blur' },
        ],
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        chufa: [
          { required: true, message: '请选择触发条件', trigger: 'blur' },
        ],
        yongjinName: [
          { required: true, message: '请输入佣金名称', trigger: 'blur' },
        ],
        yongjin: [
          { required: true, message: '请输入佣金', trigger: 'blur' },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于等于0的数字', trigger: 'blur'
          },
        ],
        dongjieDay: [
          { required: true, message: '请输入冻结期限', trigger: 'blur' },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于等于0的数字', trigger: 'blur'
          },
        ],
        fanyong: [
          { required: true, message: '请选择返佣模式', trigger: 'blur' },
        ],
        headImg: [
          { required: true, validator: imgUrlPass, trigger: 'blur' },
        ],
        goodsDetail: [
          { required: true, message: '请输入商品详情', trigger: 'blur' },
        ],
        monthRent: [
          { required: true, message: '请输入商品月租', trigger: 'blur' },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于等于0的数字', trigger: 'blur'
          },
        ],
        monthFlow: [
          { required: true, message: '请输入商品月流量', trigger: 'blur' },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于等于0的数字', trigger: 'blur'
          },
        ],
        callPrice: [
          { required: true, message: '请输入商品语音价格', trigger: 'blur' },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '请输入大于等于0的数字', trigger: 'blur'
          },
        ],
        incomeDiscount: [
          { required: true, validator: incomeDiscountRules, trigger: 'blur' },
          // { required: true, message: '请输入总部留存', trigger: 'blur' },
        ],
        addressRestrictType: [
          { required: true, message: '请选择发货地址限制', trigger: 'blur' },
        ],
        age: [
          { required: true, validator: agerules, trigger: 'blur' },
        ],
      },

      shangyouOptions: [
        {
          value: 1,
          label: '淏咖宝',
        }
      ],
      chufaOptions: [
        {
          value: 1,
          label: '激活',
        },
        {
          value: 2,
          label: '首充',
        },
      ],
      fanyongOptions: [
        {
          value: 1,
          label: '日返',
        },
        {
          value: 2,
          label: '月返',
        },
      ],

      provinces: [],
      provincesProps: {
        value: 'systemAreaId',
        label: 'systemAreaName',
        checkStrictly: false,
        multiple: true,
      },
    })


    const tiny = reactive(
      {
        content: '',
        apiKey: "m2a7guv01wyg6ihiuafs1cgdf0n92imy7zmurgpwa0i1aefb",
        init: {
          language: "zh_CN",
          placeholder: "在这里输入文字",
          min_width: 320,
          min_height: 220,
          height: 500,
          resize: "both",
          branding: false,

          font_formats:
            "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;", //字体样式
          plugins:
            "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave emoticons", //插件配置 axupimgs indent2em
          toolbar: [
            "fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | blockquote subscript superscript removeformat ",
            "styleselect formatselect fontselect fontsizeselect |  table image axupimgs media emoticons charmap hr pagebreak insertdatetime  selectall visualblocks searchreplace | code print preview | indent2em lineheight formatpainter",
          ],
          images_upload_url: '/ums/file/upload/user/pub',
          paste_data_images: false,
          images_upload_handler: (blobInfo, success, failure) => {
            const myBlob = blobInfo.blob()
            let param = new FormData()
            param.append('file', myBlob, Math.random() * 1000000 + 1 + '.jpg')
            const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
            const uesrInfo = getStore("USER_INFO_INRE") || {};
            const Authorization = getStore("USER_AUTHOR_INRE") || {
              Authorization: `'','','',3,20,''`,
            };
            let config = {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: token ? `Bearer ${token}` : '',
                username: uesrInfo.username || '',
                Authorization: Authorization.Authorization,
                platformHeadType: 'rcmsPlatform',
              }
            }
            axios.post('/ums/file/upload/user/pub', param, config).then(res => {
              if (res.data.code == '200') {
                success(res.data.data.ossUrl)
              } else {
                warningDeal(res.data.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          },

          file_picker_types: "file image media",
          // 文件上传处理函数
          file_picker_callback: function (callback, value, meta) {
            let filetype;
            if (meta.filetype == "image") {
              filetype = ".jpg, .jpeg, .png, .gif, .ico, .svg";
            } else if (meta.filetype == "media") {
              filetype = ".mp3, .mp4, .avi, .mov";
            } else {
              filetype =
                ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .jpg, .jpeg, .png, .gif, .ico, .svg";
            }
            let inputElem = document.createElement("input")
            inputElem.setAttribute("type", "file")
            inputElem.setAttribute("accept", filetype)
            inputElem.click()
            inputElem.onchange = () => {
              state.loading = true
              let file = inputElem.files[0];
              let param = new FormData()
              param.append('file', file, file.name)
              const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
              const uesrInfo = getStore("USER_INFO_INRE") || {};
              const Authorization = getStore("USER_AUTHOR_INRE") || {
                Authorization: `'','','',3,20,''`,
              };
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: token ? `Bearer ${token}` : '',
                  username: uesrInfo.username || '',
                  Authorization: Authorization.Authorization,
                  platformHeadType: 'rcmsPlatform',
                }
              }
              axios.post('/ums/file/upload/user/pub', param, config).then(res => {
                if (res.data.code == '200') {
                  callback(res.data.data.ossUrl, { title: file.name })
                } else {
                  warningDeal(res.data.msg)
                }
                state.loading = false
              }).catch(err => {
                console.log(err)
                state.loading = false
              })
            }
          },
        },
      }
    )


    function resetGoodsForm() {
      state.goodsForm = {
        incomeConfList: [{}],
      }
      goodsFormRef.value && goodsFormRef.value.resetFields()
    }

    function lookGoods() {
      lookGoodsVueRef.value.dialogShow(state.goodsForm)
    }

    //获取商品详情
    function getGoodsInfo(goodsId) {
      const obj = {
        goodsId
      }
      api.goodsDetail(obj).then(res => {
        if (res.code == '200') {
          state.goodsForm = res.data
          state.goodsForm.monthRent = res.data.monthRent / 100
          state.goodsForm.callPrice = res.data.callPrice / 100
          if (!res.data.addressRestrict && !res.data?.addressRestrictList) return
          state.goodsForm.baseAreaInfoList = res.data?.addressRestrictList || []
          // getBaseArea(state.provinces, (res.data.addressRestrict && res.data.addressRestrict.split(',')) || [])
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    //新增佣金配置
    function addYongjinConfig() {
      state.goodsForm.incomeConfList ? state.goodsForm.incomeConfList.push({}) : state.goodsForm.incomeConfList = [{}]
    }

    //删除佣金配置
    function removeYongjinCinfig(data, index) {
      if (!state.goodsForm.incomeConfList) return
      state.goodsForm.incomeConfList.splice(index, 1)
    }

    //发布商品
    function publishGoods() {
      goodsFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (state.isAdd) {
            goodsCreateHandle()
          } else {
            goodsModifyHandle()
          }
        }
      })
    }

    function goodsCreateHandle() {
      state.goodsForm.addressRestrictList = []
      getAddressRestrictList(state.provinces, state.goodsForm.baseAreaInfoList)
      const obj = {
        ...state.goodsForm,
        callPrice: state.goodsForm.callPrice * 100,
        monthRent: state.goodsForm.monthRent * 100,
      }
      api.goodsCreate(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          router.go(-1)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function goodsModifyHandle() {
      state.goodsForm.addressRestrictList = []
      getAddressRestrictList(state.provinces, state.goodsForm.baseAreaInfoList)
      const obj = {
        ...state.goodsForm,
        callPrice: state.goodsForm.callPrice * 100,
        monthRent: state.goodsForm.monthRent * 100,
      }
      api.goodsModify(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          router.go(-1)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getAddressRestrictList(arList, list) {
      arList && arList.map(items => {
        list && list.map(item => {
          if (typeof item == 'string') {
            if (item == items.systemAreaId) {
              state.goodsForm.addressRestrictList.push({
                areaId: items.systemAreaId,
                name: items.systemAreaName,
              })
            }
          } else if (typeof item == 'object' && item.length > 0) {
            if (item[item.length - 1] == items.systemAreaId) {
              state.goodsForm.addressRestrictList.push({
                areaId: items.systemAreaId,
                name: items.systemAreaName,
              })
            }
          }
        })
        if (items.children && items.children.length > 0) {
          getAddressRestrictList(items.children, list)
        }
      })
    }

    function noToHandle() {
      noToAddDialogRef.value.dialogShow(state.goodsForm.baseAreaInfoList || [])
    }

    function noToDialogClose(data) {
      if (!data || (data?.length == 0)) return
      state.goodsForm.baseAreaInfoList = data
    }

    function addressRestrictTypeChange(e) {
      state.goodsForm.baseAreaInfoList = []
    }

    function getBelongAreaList() {
      api.productBelongAreaList().then(res => {
        if (res.code == '200') {
          state.provinces = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function uploadImg() {
      uploadInputRef.value.click()
    }

    //上传文件
    async function uploadChange(e) {
      const fileForm = {}
      fileForm.file = e.target.files[0]
      fileForm.fileName = e.target.files[0].name
      await uploadFile(fileForm)
      uploadInputRef.value.value = ''
    }

    function removeImg() {
      state.goodsForm.headImg = null
    }

    async function uploadFile(fileForm) {
      let path = null
      let param = new FormData()
      param.append('file', fileForm.file, fileForm.fileName)
      const token = window.localStorage.getItem("USER_TOKEN_INRE") || '';
      const uesrInfo = getStore("USER_INFO_INRE") || {};
      const Authorization = getStore("USER_AUTHOR_INRE") || {
        Authorization: `'','','',3,20,''`,
      };
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: token ? `Bearer ${token}` : '',
          username: uesrInfo.username || '',
          Authorization: Authorization.Authorization,
          platformHeadType: 'rcmsPlatform',
        }
      }
      await axios.post('/ums/file/upload/user/pub', param, config).then(res => {
        if (res.data.code == '200') {
          path = res.data.data.ossUrl
        } else {
          errorDeal(res.data, '/ums/file/upload/user/pub')
        }
      }).catch(err => {
        console.log(err)
      })
      state.goodsForm.headImg = path
    }

    function getChannelGoodsInfo(channelCode, channelGoodsCode) {
      if (!channelCode || !channelGoodsCode) {
        warningDeal('请选择上游平台并输入平台商品编码')
        return
      }
      state.getChannelGoodsLoading = true
      const obj = {
        channelCode,
        channelGoodsCode,
      }
      api.channelGoodsDetail(obj).then(res => {
        state.getChannelGoodsLoading = false
        if (res.code == '200') {
          state.goodsForm = { ...state.goodsForm, ...res.data }
          state.goodsForm.monthRent = res.data.monthRent / 100
          state.goodsForm.callPrice = res.data.callPrice / 100
          // state.goodsForm.baseAreaInfoList = (res.data.addressRestrict && res.data.addressRestrict.split(',')) || []
          if (!res.data.addressRestrict) return
          state.goodsForm.baseAreaInfoList = []
          getBaseArea(state.provinces, (res.data.addressRestrict && res.data.addressRestrict.split(',')) || [])
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
        state.getChannelGoodsLoading = false
      })
    }

    function getBaseArea(proList, _list) {
      proList.map(item => {
        _list.map(items => {
          if (item.systemAreaName == items) {
            state.goodsForm.baseAreaInfoList.push(item.systemAreaId)
          }
        })
        if (item.children && item.children.length > 0) {
          getBaseArea(item.children, _list)
        }
      })
    }

    function getChannelList() {
      api.channelList().then(res => {
        if (res.code == '200') {
          state.shangyouOptions = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    onMounted(() => {
      state.editGoodsId = route.query.goodsId || null
      state.isAdd = !state.editGoodsId
      state.titleText = state.isAdd ? '新增号卡商品' : '编辑号卡商品'
      getChannelList()
      getBelongAreaList()
      if (!state.editGoodsId) return
      getGoodsInfo(state.editGoodsId)
    })

    return {
      ...toRefs(state),
      ...toRefs(tiny),
      goodsFormRef,
      lookGoodsVueRef,
      noToAddDialogRef,
      uploadInputRef,
      resetGoodsForm,
      lookGoods,
      addYongjinConfig,
      removeYongjinCinfig,
      publishGoods,
      noToHandle,
      noToDialogClose,
      addressRestrictTypeChange,
      uploadImg,
      removeImg,
      uploadChange,
      getChannelGoodsInfo,
    }
  }
}
</script>

<style lang="scss" scoped>
.content-box {
  box-sizing: border-box;
  padding: 20px;
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-flow: column;
  .title-box {
    display: flex;
    align-items: center;
    > .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .form-box {
    flex-grow: 1;
    box-sizing: border-box;
    padding-left: 5px;
    overflow: hidden;
    overflow-y: auto;
  }
}
.f-title {
  box-sizing: border-box;
  padding: 10px 0;
  border-bottom: 1px solid #e9e9e9;
  font-size: 14px;
  font-weight: bold;
}

.yongjin-box {
  > div {
    display: flex;
    &:not(:first-of-type) {
      border-top: 1px dashed #d9d9d9;
    }
    > span {
      display: block;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    > .el-row {
      flex-grow: 1;
      align-items: center;
      .remove-icon {
        font-size: 24px;
        color: #f40;
        cursor: pointer;
        margin-left: 10px;
      }
    }
  }
}
.upload-box-img {
  width: 80px;
  height: 80px;
  border: 1px dashed #b3b3b5;
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.upload-box {
  position: relative;
  > img {
    max-width: 150px;
    max-height: 80px;
  }
  .upload-close {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    background-color: rgba($color: #000000, $alpha: 0.5);
  }
}
</style>